package com.game.dao.core;

import com.coment.po.Game;
import com.xs.build.server.websocket.channel.ClientManager;
import org.springframework.data.mongodb.repository.Aggregation;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.lang.NonNull;

import java.util.List;
import java.util.Optional;

public interface GameDao extends MongoRepository<Game, Integer> {
    default void updateAndPush(Game fullUpdate) {
        this.save(fullUpdate);
        ClientManager.sendMessageToClient(fullUpdate.getAnchorInfoId().toString(), fullUpdate);
    }

    @NonNull
    @Override
    <S extends Game> S save(@NonNull S entity);

    default Game findByIdMust(Integer integer) {
        return this.findById(integer).orElseThrow(() -> new RuntimeException("游戏不存在"+integer));
    }

    /// 复合查询 -> 获取所有未结算的游戏
    @Aggregation(pipeline = {
            "{ $match: { startTime: { $ne: null } } }",
            "{ $project: { anchorInfoId: 1 } }"
    })
    List<Integer> findAnchorInfoIdsByStartTimeNotNull();


    /// 复合查询 -> 查看玩家是否在游戏中
    @Aggregation(pipeline = {
            "{ $match: { userInfoIdSeat: { $elemMatch: { id: ?0 } } } }",
            "{ $project: { _id: 1 } }",
            "{ $limit: 1 }"
    })
    boolean checkIfThePlayerIsInTheGame(Integer userInfoId);

    /// id查询
    @NonNull
    @Override
    Optional<Game> findById(@NonNull Integer integer);

    /// id查询
    default Game findOrCreateById(Integer anchorInfoId){
        return findById(anchorInfoId).orElseGet(() -> this.save(new Game(anchorInfoId)));
    }

    List<Game> findAllByStartTimeIsNear(Long startTime);

    List<Game> findAllByStartTime(Long startTime);

    List<Game> findAllByStartTimeNotNull(Long startTime);
}
